<template>
  <el-table class="table" :data="data" style="width: 100%" border>
    <el-table-column type="index" label="序号" width="60" />
    <el-table-column prop="key" label="key">
      <template #default="{ row }">
        <el-input
          v-model="row.key"
          :disabled="disabled"
          @blur="blur"
        ></el-input>
      </template>
    </el-table-column>
    <el-table-column prop="value" label="value">
      <template #default="{ row }">
        <el-input
          v-model="row.value"
          :disabled="disabled"
          @blur="blur"
        ></el-input>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scoped">
        <div class="opera">
          <span class="btn add" @click="add">增加</span>
          <span class="btn del" @click="del(scoped)">删除</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="error" label="结果">
      <template #default="{ row }">
        <div :class="row.error ? 'error' : 'pass'">
          {{ row.error ? "格式错误" : "验证通过" }}
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import { ref, watch } from "vue"

let props = defineProps({
  target: {
    type: Object,
    default: () => {},
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})
let emit = defineEmits(["update"])
let defaultItem = { key: "", value: "", error: false }
let data = ref([])

function add() {
  data.value.push(JSON.parse(JSON.stringify(defaultItem)))
}
function del(scoped) {
  if (data.value.length !== 1) {
    let { $index } = scoped
    data.value.splice($index, 1)
  }
}
function blur() {
  let successNum = 0
  data.value.forEach(item => {
    if (
      (item.key !== "" && item.value == "") ||
      (item.key === "" && item.value !== "")
    ) {
      // 错误
      item.error = true
    } else {
      // 正确
      successNum++
      item.error = false
    }
  })
  // 验证是否全部通过
  if (successNum == data.value.length) {
    // 转换数据成对象
    const updateObj = {}
    data.value.forEach(e => {
      if (e.key) updateObj[e.key] = e.value
    })
    emit("update", updateObj)
  }
}

watch(
  () => props.target,
  target => {
    data.value = []
    for (const k in target) {
      data.value.push({
        key: k,
        value: target[k],
        error: false,
      })
    }
    // 默认值
    if (!data.value.length)
      data.value = [JSON.parse(JSON.stringify(defaultItem))]
  },
  {
    immediate: true,
    deep: true,
  }
)
</script>
<style scoped lang="scss">
.opera {
  text-align: center;
  .btn {
    // width: 50px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    cursor: pointer;
    margin-right: 20px;
  }
  .add {
    color: #00f;
  }
  .del {
    color: #f00;
  }
}
.pass {
  color: #51d6a9;
}
.error {
  color: #f00;
}
</style>
